﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace Wolfbyte.Core.Data
{
    public static class Local
    {
        [ThreadStatic]
        private static IDictionary<string, object> LocalDictionary;

        private static readonly string ContextDataKey = new object().GetHashCode().ToString();

        private static IDictionary<string, object> GetLocalData()
        {
            if (IsRunningInWeb())
            {
                return (HttpContext.Current.Items[ContextDataKey] ??
                    (
                        HttpContext.Current.Items[ContextDataKey]
                                    = new Dictionary<string, object>()
                    )) as IDictionary<string, object>;
            }
            else
            {
                return LocalDictionary ??
                    (
                        LocalDictionary = new Dictionary<string, object>()
                    );
            }
        }

        private static bool IsRunningInWeb()
        {
            return HttpContext.Current != null;
        }

        public static IDictionary<string, object> Data
        {
            get
            {
                return GetLocalData();
            }
        }
    }
}